package org.linlinjava.litemall.wx.web;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.vo.TimeLineVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 时间轴信息发布
 */
@RestController
@RequestMapping("/wx/timeline")
@Validated
public class WxTimelineController {

    private final Log logger = LogFactory.getLog(WxSearchController.class);

    @Autowired
    private LitemallTimelineService timelineService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;



    /**
     * 订单列表
     *
     * @param page     分页页数
     * @param limit     分页大小
     * @param sort     排序字段
     * @param order     排序方式
     * @return 订单列表
     */
    @GetMapping("orderlist")
    public Object orderList(@LoginUser Integer userId,
                       @RequestParam(defaultValue = "false") Boolean isAdmin,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {

        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        //分页查询订单数据
        List<LitemallOrder> orderList;
        if(isAdmin){
            //管理员数据
            List<Short> orderStatus = new ArrayList<Short>();
            orderList = orderService.queryStatusArray(orderStatus , page, limit, sort, order);
        }else {
            //用户数据
            List<Short> orderStatus = OrderUtil.orderStatus(0);
            orderList = orderService.queryByOrderStatus(userId, orderStatus, page, limit, sort, order);
        }

        ArrayList<Object> orderVoList = new ArrayList<>();
        LinkedHashMap<String, ArrayList<Object>> orderVoMap = new LinkedHashMap<>();

        for (LitemallOrder o : orderList) {
            String[] split = o.getAddTime().toString().split("T");
            if (orderVoMap.get(split[0]) == null) {
                orderVoMap.put(split[0],new ArrayList<>());
            }

            //拼装订单信息
            Map<String, Object> orderVo = new HashMap<>();
            orderVo.put("id", o.getId());
            orderVo.put("time",split[1]);
            orderVo.put("isAdmin",isAdmin);
            orderVo.put("addTime",o.getAddTime());
            orderVo.put("orderSn", o.getOrderSn());
            orderVo.put("actualPrice", o.getActualPrice());
            orderVo.put("orderStatusText", OrderUtil.orderStatusText(o));
            orderVo.put("refund", o.getOrderStatus()==202?true:false);
            orderVo.put("ship", o.getOrderStatus()==201?true:false);
            orderVo.put("aftersaleStatus",o.getAftersaleStatus());

            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(o.getId());
            List<Map<String, Object>> orderGoodsVoList = new ArrayList<>(orderGoodsList.size());
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                Map<String, Object> orderGoodsVo = new HashMap<>();
                orderGoodsVo.put("id", orderGoods.getId());
                orderGoodsVo.put("goodsId",orderGoods.getGoodsId());
                orderGoodsVo.put("goodsName", orderGoods.getGoodsName());
                orderGoodsVo.put("number", orderGoods.getNumber());
                orderGoodsVo.put("picUrl", orderGoods.getPicUrl());
                orderGoodsVo.put("specifications", orderGoods.getSpecifications());
                orderGoodsVo.put("price",orderGoods.getPrice());
                orderGoodsVoList.add(orderGoodsVo);
            }
            orderVo.put("goodsList", orderGoodsVoList);
            //根据日期map添加进Map的value
            orderVoMap.get(split[0]).add(orderVo);
        }

        //对时间进行排序
        ArrayList<String> keyList = new ArrayList<>();
        for (String key:orderVoMap.keySet()) {
            keyList.add(key);
        }
        //对时间进行排序
        keyList.sort((t1, t2) -> t2.compareTo(t1));

        //将每个日期分开放进集合
        for (String key:keyList) {
            LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
            linkedHashMap.put("dayTime",key);
            linkedHashMap.put("orderVo",orderVoMap.get(key));
            orderVoList.add(linkedHashMap);
        }
        return ResponseUtil.okList(orderVoList,orderList);
    }


    /**
     * 发布列表
     *
     * @param page     分页页数
     * @param limit     分页大小
     * @param sort     排序字段
     * @param order     排序方式
     * @return 订单列表
     */
    @GetMapping("timelinelist")
    public Object timelineList(
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {

        ArrayList<Object> timeLineVoList = new ArrayList<>();
        LinkedHashMap<String, ArrayList<Object>> timeLineVoMap = new LinkedHashMap<>();

        //TODO 分页失效暂时找不到解决办法
        List<LitemallTimeline> timelines = timelineService.queryList(page, limit, sort, order);
        //根据日期将LitemallTimeline添加进Map的value
        for (LitemallTimeline timeline:timelines) {
            String[] split = timeline.getAddTime().toString().split("T");
            if (timeLineVoMap.get(split[0]) == null){
                timeLineVoMap.put(split[0],new ArrayList<>());
            }

            //给查寻出来的时间加上浏览量
            timeline.setLookNumber(timeline.getLookNumber()+1);
            timelineService.updateById(timeline);

            LitemallUser user = userService.findById(timeline.getUserId());
            TimeLineVo timeLineVo = new TimeLineVo();
            timeLineVo.setAddTime(timeline.getAddTime());
            timeLineVo.setContent(timeline.getContent());
            timeLineVo.setAdmin(timeline.getIsAdmin());
            timeLineVo.setLookNumber(timeline.getLookNumber());
            timeLineVo.setPicUrls(timeline.getPicUrls());
            timeLineVo.setThumbUp(timeline.getThumbUp());
            timeLineVo.setUserId(timeline.getUserId());
            timeLineVo.setId(timeline.getId());
            timeLineVo.setAvatar(user.getAvatar());
            timeLineVo.setNickname(user.getNickname());
            timeLineVoMap.get(split[0]).add(timeLineVo);
        }

        ArrayList<String> keyList = new ArrayList<>();
        for (String key:timeLineVoMap.keySet()) {
            keyList.add(key);
        }
        //对时间进行排序
        keyList.sort((t1, t2) -> t2.compareTo(t1));
        //将每个日期分开放进集合
        for (String key:keyList) {
            LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
            linkedHashMap.put("dayTime",key);
            linkedHashMap.put("timeLineVo",timeLineVoMap.get(key));
            timeLineVoList.add(linkedHashMap);
        }

        return ResponseUtil.okList(timeLineVoList,timelines);
    }




    /**
     * 发布日常
     *
     * @param userId   用户ID
     * @param timeline 时间轴发布信息
     * @return 操作结果
     */
    @PostMapping("submit")
    public Object submit(@LoginUser Integer userId, @RequestBody LitemallTimeline timeline) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        String content = timeline.getContent();
        if (StringUtils.isEmpty(content)) {
            return ResponseUtil.badArgument();
        }

        timeline.setId(null);
        timeline.setUserId(userId);
        timelineService.add(timeline);
        return ResponseUtil.ok();
    }

    /**
     * 删除日常
     *
     * @param userId   用户ID
     * @param body 时间轴发布信息的id
     * @return 操作结果
     */
    @PostMapping("delete")
    public Object submit(@LoginUser Integer userId, @RequestBody String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer timeVoId = JacksonUtil.parseInteger(body, "timeVoId");
        Integer TimeUserId = JacksonUtil.parseInteger(body, "userId");
        Boolean isAdmin = JacksonUtil.parseBoolean(body, "isAdmin");

        if (timeVoId == null && TimeUserId == null){
            return ResponseUtil.badArgument();
        }
        if (isAdmin){
            timelineService.deleteById(timeVoId);
        }else if(TimeUserId.equals(userId)){
            timelineService.deleteById(timeVoId);
        }else {
            return ResponseUtil.fail(600,"无权限");
        }
        return ResponseUtil.ok();
    }


}
